<template>
  <div class="box1">
    <el-row>
      <el-col :span="6" :offset="2">
        <el-card class="card1">
          <div class="heard1">
            在线用户<span style="font-size: 12px"
              >（点击聊天气泡开始聊天）</span
            >
          </div>

          
          <div style="padding: 10px 0">
            <span>点击联系管理员</span>
          <i
              class="el-icon-phone-outline"
              style="margin-left: 10px; font-size: 16px; cursor: pointer"
              @click="openEmil"
            ></i>
            <span
              style="font-size: 12px; color: limegreen; margin-left: 5px"
              v-if="openemil"
              >正在赶来的路上...</span
            >
          </div>

          <div
            style="padding: 10px 0"
            v-for="(user, index) in users"
            :key="index"
          >
            
            <span>{{ user.userName == ManageUser.filter(user => user=="ww")[0] ? '管理员' :  user.userName }}</span>
            <i
              class="el-icon-chat-dot-round"
              style="margin-left: 10px; font-size: 16px; cursor: pointer"
              @click="chat(user)"
            ></i>
            <span
              style="font-size: 12px; color: limegreen; margin-left: 5px"
              v-if="user.userName === chatUser"
              >chatting...</span
            >
          </div>
        </el-card>
      </el-col>

      <el-col :span="6">
        <div class="box2">
          <div style="text-align: center; line-height: 50px">
            Web聊天室（{{ chatUser }}）
          </div>

          <div
            style="height: 350px; overflow: auto; border-top: 1px solid #ccc"
            v-html="content"
          ></div>

          <div style="height: 200px">
            <textarea v-model="text"></textarea>

            <div style="text-align: right; padding-right: 10px">
              <el-button type="primary" size="mini" @click="send"
                >发送</el-button
              >
            </div>
          </div>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import websocketApi from "@/api/websocket/websocketApi";
import UserApi from "@/api/user/UserApi"
let socket;
let that;
export default {
  name: "CustomerManagement",
  data() {
    return {
      circleUrl:
        "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
      user: {},
      isCollapse: false,
      users: [],
      chatUser: "",
      text: "",
      messages: [],
      content: "",
      userinfo: {},
      remoteUserImg: "",
      openemil: false,
      ManageUser: []
    };
  },
  created() {
    this.userinfo = JSON.parse(sessionStorage.getItem("userInfo"));
    // console.log(this.userinfo.avatar)
    // console.log(websocketApi.url)
    var flage=false;
    this.queryManageUser(flage);
    that = this;
    this.init();
  },
  methods: {
    queryManageUser(flage){
      UserApi.queryManageUser(flage).then(res => {
        if(!flage){
            this.ManageUser=JSON.parse(res.data.data);
        }
      console.log(res.data)
      console.log(this.ManageUser.filter(user => user=="ww")[0])
    })
    },
    openEmil(){
      if (this.openemil) {
        this.$message.warning("请不要重复点击，管理员正在赶来的路上......")
      } else {
        this.openemil=true;
        this.queryManageUser(true);
        this.$message.success("管理员正在赶来的路上......")
      }
    },
    chat(user) {
      this.chatUser = user.userName;
      // console.log(this.chatUser)
    },

    send() {
      if (!this.chatUser) {
        this.$message({ type: "warning", message: "请选择聊天对象" });
        return;
      } else if (!this.text) {
        this.$message({ type: "warning", message: "请输入内容" });
        return;
      } else if (typeof WebSocket == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");
        // 消息体{ from: "zhang", fromImg: "xxx" to: "admin", text: "聊天文本" };
        let message = {from: sessionStorage.getItem("userName"), fromImg: this.userinfo.avatar, to: this.chatUser, text: this.text}
        // 将组装好的json发送给服务端，由服务端进行转发
         socket.send(JSON.stringify(message));  
         this.messages.push({user: sessionStorage.getItem("userName"), text: this.text})
          // 构建消息内容，本人消息
        this.createContent(null, sessionStorage.getItem("userName"), message.text);
        console.log(message)
        this.text = "";
      }
    },

    // 这个方法是用来将 json的聊天消息数据转换成 html的。
    createContent(remoteUser, nowUser, text) {
      let html;
      // 当前用户消息
      if (nowUser) {
        // nowUser 表示是否显示当前用户发送的聊天消息，绿色气泡
        html =
          "<div class='el-row' style='padding: 5px 0'>\n" +
          "  <div class='el-col el-col-22' style='text-align: right; padding-right: 10px'>\n" +
          "    <div class='tip left' style='background-color: forestgreen; color: white; text-align: center; border-radius: 10px; font-family: sans-serif; padding: 10px; width:auto; display:inline-block !important; display:inline;'>" +
          text +
          "</div>\n" +
          "  </div>\n" +
          "  <div class='el-col el-col-2'>\n" +
          "  <span class='el-avatar el-avatar--circle' style='height: 40px; width: 40px; line-height: 40px;'>\n" +
          "    <img src='" +
          this.userinfo.avatar +
          "' style='object-fit: cover;'>\n" +
          "  </span>\n" +
          "  </div>\n" +
          "</div>";
      } else if (remoteUser) {
        // remoteUser表示远程用户聊天消息，蓝色的气泡
        html =
          "<div class='el-row' style='padding: 5px 0'>\n" +
          "  <div class='el-col el-col-2' style='text-align: right'>\n" +
          "  <span class='el-avatar el-avatar--circle' style='height: 40px; width: 40px; line-height: 40px;'>\n" +
          "    <img src='"+this.remoteUserImg+"' style='object-fit: cover;'>\n" +
          "  </span>\n" +
          "  </div>\n" +
          "  <div class='el-col el-col-22' style='text-align: left; padding-left: 10px'>\n" +
          "    <div class='tip right' style='background-color: deepskyblue; color: white; text-align: center; border-radius: 10px; font-family: sans-serif; padding: 10px; width:auto; display:inline-block !important; display:inline;'>" +
          text +
          "</div>\n" +
          "  </div>\n" +
          "</div>";
      }
      // console.log(html);
      this.content += html;
    },

    init() {
      if (typeof WebSocket == "undefined") {
        console.log("您的浏览器不支持WebSocket");
      } else {
        console.log("您的浏览器支持WebSocket");

        if (socket != null) {
          socket.close();
          socket = null;
        }
        // 创建websocket对象
        socket = new WebSocket(
          websocketApi.url + this.userinfo.id + "/" + this.userinfo.name
        );

        // websocket已连接调用的方法
        socket.onopen = function () {
          console.log("websocket已打开");
        };
        //  浏览器端收消息，获得从服务端发送过来的文本消息
        socket.onmessage = function (msg) {
          console.log("收到数据====" + msg.data);
          var uu = JSON.parse(msg.data);
          console.log(uu);
          if (uu.users) {
            // 获取当前连接的所有用户信息，并且排除自身，自己不会出现在自己的聊天列表里
            that.users = uu.users.filter(
              (user) => user.userName !== sessionStorage.getItem("userName")
            );
            console.log(that.users);
          } else {
            //  如果服务器端发送过来的json数据 不包含 users 这个key，那么发送过来的就是聊天文本json数据
            //  // {from: 'ww',  fromImg: '/User-Img/eee61b33-0365-4467-844e-42f152693afe.jpg', "text": '咕咕iuo'}
            if (uu.from === that.chatUser) {
              that.messages.push(uu);
              // 构建消息内容
              that.remoteUserImg=uu.fromImg;
              that.createContent(uu.from, null, uu.text);
            }
          }
        };
        //关闭事件
        socket.onclose = function () {
          console.log("websocket已关闭");
        };
        //发生了错误事件
        socket.onerror = function () {
          console.log("websocket发生了错误");
        };
      }
    },
  },
};
</script>

<style scoped>
.box1 {
  margin: 2% auto;
  position: relative;
  /* background: pink; */
}
.card1 {
  width: 300px;
  height: 300px;
  color: #333;
  float: right;
  position: relative;
  right: 8%;
}
.heard1 {
  padding-bottom: 10px;
  border-bottom: 1px solid #ccc;
}
.box2 {
  width: 800px;
  margin: 0 auto;
  background-color: white;
  border-radius: 5px;
  box-shadow: 0 0 10px #ccc;
}
textarea {
  height: 160px;
  width: 100%;
  padding: 20px;
  border: none;
  border-top: 1px solid #ccc;
  border-bottom: 1px solid #ccc;
  outline: none;
  box-sizing: border-box;
}

.tip {
  color: white;
  text-align: center;
  border-radius: 10px;
  font-family: sans-serif;
  padding: 10px;
  width: auto;
  display: inline-block !important;
  display: inline;
}

.right {
  background-color: deepskyblue;
}
.left {
  background-color: forestgreen;
}
</style>
